
import os
import uuid

from fastapi import APIRouter, File, Form, UploadFile
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.exceptions import HTTPException

from core.config import response_body 
router = APIRouter(prefix='/file',tags=['文件操作'])



# 上传文件
@router.post("/upload/")
async def upload_file(
    file: UploadFile = File(...),
    file_location: str = Form(description='文件存储位置',default='~/Desktop/upload'),
):
    contents = await file.read()
    uuid_file_name=f"{uuid.uuid4().hex}.{file.filename.split('.')[-1]}"
    # 写之前，如果没有改文件夹，需要创建，需要注意 ～代表用户目录，需要展开
    import os
    if not os.path.exists(os.path.expanduser(file_location)):
        os.makedirs(os.path.expanduser(file_location))
    # 写入本地文件
    with open(f"{os.path.expanduser(file_location)}/{uuid_file_name}", "wb") as f: 
        f.write(contents)
    response_body['msg'] = '上传成功'
    response_body['data'] = {
        "uuid_file_name": uuid_file_name,
        "file_name": file.filename,
        "file_location": os.path.expanduser(file_location)+"/"+uuid_file_name,
        "file_size": len(contents)
    }
    return response_body
# 下载文件
@router.get("/1/{uuid_file_name}")
async def download_file(
    uuid_file_name: str,
):
    file_location = '~/Desktop/upload'
    file_path = f"{os.path.expanduser(file_location)}/{uuid_file_name}"
    print(file_path)
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="File not found")
    return FileResponse(file_path)
